package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import org.apache.ibatis.annotations.Param;
import org.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/1/31.
 */
@Service
public class WmsReportsService extends BaseService<WmsReportsMapper, WmsHarvestDaily> {
    @Resource
    private WmsStockMapper wmsStockMapper;
    @Resource
    private WmsShipmentOrderMapper wmsShipmentOrderMapper;
    @Resource
    private WmsLibraryPositionMapper wmsLibraryPositionMapper;
    @Resource
    private WmsPickingMapper wmsPickingMapper;

    /**
     * 收货日报表分页查询
     *
     * @param entity 实体
     * @return Page<WmsLine>
     */
    @BaseServiceDescribe(moduleName = "收货日报表", btnName = "分页查询")
    public Page<WmsHarvestDaily> baseHarvestPage(WmsHarvestDaily entity) throws Exception {
        Page<WmsHarvestDaily> list = null;
        try {
            PageHelper.startPage(entity.getPage(), entity.getRows());
            list = (Page<WmsHarvestDaily>) dao.baseHarvestPage(entity);
            return list;
        } catch (Exception e) {
            throw new ServiceException("收货日报表分页查询失败", e);
        }
    }

    /**
     * 收货日报表导出
     * @param ids
     * @param map
     * @return
     */
    @BaseServiceDescribe(moduleName = "收货日报表导出", btnName = "收货日报表导出")
    public List<WmsHarvestDaily> getOutPutHarvest(List<String> ids,Map map) {
        List<WmsHarvestDaily> list = dao.getOutPutHarvest(ids, map);
        return list;

    }

    /**
     * 上架日报表分页查询
     *
     * @param entity 实体
     * @return Page<WmsLine>
     */
    @BaseServiceDescribe(moduleName = "上架日报表", btnName = "分页查询")
    public Page<WmsShelvesDailies> baseWmsShelvesDailiesPage(WmsShelvesDailies entity) throws Exception {
        Page<WmsShelvesDailies> list = null;
        try {
            PageHelper.startPage(entity.getPage(), entity.getRows());
            list = (Page<WmsShelvesDailies>) dao.baseWmsShelvesDailiesPage(entity);
            return list;
        } catch (Exception e) {
            throw new ServiceException("上架日报表分页查询失败", e);
        }
    }

    /**
     * 上架日报表导出
     * @param ids
     * @param map
     * @return
     */
    @BaseServiceDescribe(moduleName = "收货日报表导出", btnName = "收货日报表导出")
    public List<WmsShelvesDailies> getOutPutShelves(List<String> ids,Map map) {
        return dao.getOutPutShelves(ids, map);
    }


    /**
     * 货品库存总数量
     * @return
     */
    @BaseServiceDescribe(moduleName = "货品库存总数量", btnName = "货品库存总数量")
    public void quantity() throws Exception{
        List<WmsStock> list=null;
            list=dao.quantity();
            if (list.size()>0){
                WmsGoodsBalance wgb=null;
                List<WmsGoodsBalance> lists=new ArrayList<WmsGoodsBalance>();
                for (int i=0;i<list.size();i++){
                    SimpleDateFormat format = new SimpleDateFormat("M");
                    Calendar cals = Calendar.getInstance();
                    cals.add(Calendar.MONTH, -1);//查询上一个月
                    Date m = cals.getTime();
                    String mon = format.format(m);//上个月
                    int syear = cals.get(Calendar.YEAR);
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH )+1;
                    //查询上月库存s
                    WmsGoodsBalance wgbs=dao.syStock(list.get(i).getHpid(),String.valueOf(syear),mon);
                    wgb=new WmsGoodsBalance();
                    wgb.setId(UUIDUtils.uuid());
                    wgb.setHpid(list.get(i).getHpid());//货品id
                    wgb.setHpbh(list.get(i).getHpbh());//货品编号
                    wgb.setHpmc(list.get(i).getHpmc());//货品名
                    wgb.setN(String.valueOf(year));//年
                    wgb.setY(String.valueOf(month));//月
                    if (wgbs!=null){
                        wgb.setSyjc(wgbs.getByjc());//上月库存
                    }else {
                        wgb.setSyjc("0");//上月库存
                    }
                    wgb.setByjc(list.get(i).getKczsl());//本月库存
                    if (wgb.getHpbh()!=null){
                        lists.add(wgb);
                    }
                }
                //添加结存数据
                dao.baseInsertShelves(lists);
            }
    }

    /**
     * 进出存合并报表查询
     */
    @BaseServiceDescribe(moduleName = "进出存合并报表", btnName = "分页查询")
    public Page<WmsOutStock> outStock(WmsOutStock entity) throws Exception{
        Page<WmsOutStock> list = null;
        try {
            PageHelper.startPage(entity.getPage(), entity.getRows());
            if (entity.getSj()!=null && !entity.equals("")){
                String date =entity.getSj();
                date = date.replace("Z", " UTC");//注意是空格+UTC
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
                Date d = format2.parse(date);
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy");//注意格式化的表达式
                entity.setN(format1.format(d).toString());
                SimpleDateFormat format3 = new SimpleDateFormat("M");//注意格式化的表达式
                entity.setY(format3.format(d).toString());
            }

            //获取当前年月
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH )+1;
            if (entity.getN()!=null && entity.getY()!=null){
                String ny=entity.getN()+"-"+entity.getY();
                entity.setNy(ny);
            if (entity.getN().equals(String.valueOf(year)) && entity.getY().equals(String.valueOf(month))){ //判断传过来的月份是否为当前月
                entity.setN("");
                entity.setY("");
                }
            list = (Page<WmsOutStock>) dao.outStock(entity);
            }
            //判断传过来的月份是否为当前月 如果是当前月 计算本月结存 把当前本月结存放入上月结存中
            if (list !=null && list.size()>0){
                SimpleDateFormat format = new SimpleDateFormat("M");
                Calendar cals = Calendar.getInstance();
                cals.add(Calendar.MONTH, -1);//查询上一个月
                Date m = cals.getTime();
                String mon = format.format(m);//上个月
                int syear = cals.get(Calendar.YEAR);
                for(int i=0;i<list.size();i++){
                    if (list.get(i).getByjc()==null){
                        int bysl=Integer.parseInt(list.get(i).getShsl())-Integer.parseInt(list.get(i).getZjck())+Integer.parseInt(list.get(i).getZjrk())-Integer.parseInt(list.get(i).getCksl())-Integer.parseInt(list.get(i).getHpslck());
                        list.get(i).setByjc(String.valueOf(bysl));
                        WmsGoodsBalance wgb= dao.byjcselect(String.valueOf(syear),mon,list.get(i).getHpid());
                        list.get(i).setSyjc(wgb.getByjc());
                    }
                }
            }
            return list;
        } catch (Exception e) {
            throw new ServiceException("进出存合并报表分页查询失败", e);
        }
    }

    /**
     * 进出存合并报表导出
     * @param idList
     * @param map
     * @return
     */
    @BaseServiceDescribe(moduleName = "进出存合并报表导出", btnName = "进出存合并报表导出")
    public List<WmsOutStock> getoutStock(@Param("list") List<String> idList, @Param("Map") Map map) throws Exception{
        String date =map.get("sj").toString();
        date = date.replace("Z", " UTC");//注意是空格+UTC
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
         Date d = format2.parse(date);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy");//注意格式化的表达式
        map.put("n",format1.format(d).toString());
        SimpleDateFormat format3 = new SimpleDateFormat("M");//注意格式化的表达式
        map.put("y",format3.format(d).toString());
        List<WmsOutStock> list=new ArrayList<WmsOutStock>();
        //获取当前年 月
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH )+1;
        if (map.get("n")!=null && map.get("y")!=null){
            String ny=map.get("n")+"-"+map.get("y");
            map.put("ny",ny);
            if (map.get("n").equals(String.valueOf(year)) && map.get("y").equals(String.valueOf(month))){ //判断传过来的月份是否为当前月
                map.put("n","");
                map.put("y","");
            }
            list=dao.getoutStock(idList, map);
        }
        if (list!=null && list.size()>0){
            SimpleDateFormat format = new SimpleDateFormat("M");
            Calendar cals = Calendar.getInstance();
            cals.add(Calendar.MONTH, -1);//查询上一个月
            Date m = cals.getTime();
            String mon = format.format(m);//上个月
            int syear = cals.get(Calendar.YEAR);
            for(int i=0;i<list.size();i++){
                if (list.get(i).getByjc()==null){
                    int bysl=Integer.parseInt(list.get(i).getShsl())-Integer.parseInt(list.get(i).getZjck())+Integer.parseInt(list.get(i).getZjrk())-Integer.parseInt(list.get(i).getCksl())-Integer.parseInt(list.get(i).getHpslck());
                    list.get(i).setByjc(String.valueOf(bysl));
                    WmsGoodsBalance wgb= dao.byjcselect(String.valueOf(syear),mon,list.get(i).getHpid());
                    list.get(i).setSyjc(wgb.getByjc());
                }
            }
        }
        return list;
    }

    /**
     * 出库日报表分页查询
     */
    @BaseServiceDescribe(moduleName = "出库日报表", btnName = "分页查询")
    public Page<Wmslibrary> baselibraryPage(@Param("Wmslibrary") Wmslibrary entity) throws Exception{
        Page<Wmslibrary> list = null;
        try {
            PageHelper.startPage(entity.getPage(), entity.getRows());
            list = (Page<Wmslibrary>) dao.baselibraryPage(entity);
            return list;
        } catch (Exception e) {
            throw new ServiceException("出库日报表分页查询失败", e);
        }
    }

    /**
     * 出库日报表导出
     * @param idList
     * @return
     */
    @BaseServiceDescribe(moduleName = "出库日报表导出", btnName = "出库日报表导出")
    public List<Wmslibrary> getoutlibrary(@Param("list") List<String> idList, @Param("Map") Map map){
        return dao.getoutlibrary(idList, map);
    }

    /**
     * 库存报表查询
     */
    @BaseServiceDescribe(moduleName = "库存报表查询", btnName = "库存报表查询")
    public Page<WmsStockReport> getstock(@Param("WmsStockReport") WmsStockReport entity )throws Exception{
        Page<WmsStockReport> list=null;
        try {
            PageHelper.startPage(entity.getPage(), entity.getRows());
            list = (Page<WmsStockReport>) dao.getstock(entity);
            return list;
        }catch (Exception e){
            throw new ServiceException("库存报表分页查询", e);
        }
    }

    /**
     * 库存报表导出
     * @param idList
     * @return
     */
    @BaseServiceDescribe(moduleName = "库存报表导出", btnName = "库存报表导出")
    public List<WmsStockReport> getstockout(@Param("list") List<String> idList, @Param("Map") Map map){
        return dao.getstockout(idList, map);
    }
    /**
     * 合计统计报表
     */
    @BaseServiceDescribe(moduleName = "合计统计报表", btnName = "合计统计报表")
    public JSONObject countTjBySj(String sj,String ckid) throws Exception {
        JSONObject object = new JSONObject();
        //有库存的货品数
        Integer stockSl = wmsStockMapper.countSpslByRq(sj,ckid);
        //整箱数和散箱数
        List<WmsBox> box=wmsStockMapper.countZsslByRq(sj,ckid);
        if(box.size()>0){
        for(WmsBox b:box){
            if("0".equals(b.getZslx())){
                object.put("zxsl",b.getSl());
            }
            if("1".equals(b.getZslx())){
                object.put("sxsl",b.getSl());
            }
        }}else {
            object.put("zxsl",0);
            object.put("sxsl",0);
        }
        //发运订单数
        Integer fyddSl = wmsShipmentOrderMapper.getDdsl(sj,ckid);
        object.put("goodsSl", stockSl);
        object.put("ckdSl",fyddSl);
        //空库位数量
        Integer kkw=wmsLibraryPositionMapper.getEmptyCount(ckid);
        object.put("kkw",kkw);
        //库存数量（不包含集货库位）
        Integer kcsl=wmsStockMapper.getSum(ckid);
        object.put("kcsl",kcsl);
        //待捡货数量总和
        Integer djhsl=wmsStockMapper.getDjhSum(ckid);
        object.put("djhsl",djhsl);
        //总出库数量
        Integer zcksl=wmsPickingMapper.getZckslSum(ckid,sj);
        object.put("zcksl",zcksl);
        return object;
    }

    /**
     * 货品出货量
     */
    @BaseServiceDescribe(moduleName = "货品出货量", btnName = "分页查询")
    public List<WmsPicking> shipmentGoods(WmsPicking entity) throws Exception{
        try {
            List<WmsPicking> list = dao.shipmentGoods(entity);
            return list;
        } catch (Exception e) {
            throw new ServiceException("货品出货量", e);
        }
    }
}
